<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Send;
use App\Api\Helpers\ApiResponse;
use App\Models\Owner;
use App\Models\OwnerItem;
use App\Models\User;
use App\Services\SendService;
use Carbon\Carbon;
use Dcat\Admin\Controllers\AdminController;
use Dcat\Admin\Form;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Models\Administrator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 短信推送
 * Class SmsOperationController
 * @package App\Admin\Controllers
 */
class SmsOperationController extends AdminController
{
    use ApiResponse;

    protected $sendService;
    protected $ownerModel;

    public function __construct(SendService $sendService, Owner $owner)
    {
        $this->sendService = $sendService;
        $this->ownerModel = $owner;
    }

    /**
     * 短信推送首页
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        $admins = $this->getAllNotNullMobileAdmins();

        // 获取“已经抄表”and“未支付的用户”的租客
        $owners = $this->getMeterReadAndNotPayOwners();

        // 获取最早一期的订单
        return $content
            ->title('短信群发中心')
            ->body(view('admin.send.sms_operation', compact('admins', 'owners')));
    }

    private function getMeterReadAndNotPayOwners()
    {
        return Owner::query()->with(
            [
                'items' => function ($query) {
                    $query->whereNull("pay_at")
                        ->whereNotNull('total_amount')
                        ->where('started_at', '<', Carbon::now());
                },
            ]
        )->get();
    }

    /**
     * 获取有手机号码的管理员
     * @return \Illuminate\Support\Collection
     */
    private function getAllNotNullMobileAdmins()
    {
        $admins = DB::table("admin_users")->select(['id', 'username', 'mobile'])->whereNotNull("mobile")->get();

        return $admins;
    }

    /**
     * 根据合同（租客）进行群发
     * @param $templateId
     * @param array $owners
     * @param SendService $sendService
     * @return mixed
     */
    public function sendOwnersByTemplate($templateId)
    {
        $owners = request()->input('ids');

        $query = OwnerItem::query()->with(['owner.user'])
            ->whereNull("pay_at")
            ->whereNotNull('total_amount')
            ->where('started_at', '<', Carbon::now());

        if ($owners) {
            $query = $query->whereHas(
                'owner',
                function ($query) use ($owners) {
                    $query->whereIn('id', $owners);
                }
            );
        }

        $query->get()->each(
            function ($ownerItem) use ($templateId, $owners) {
                // 发送短信
                $this->sendService->qcloudByTemplate(
                    $ownerItem->owner->user->mobile,
                    $templateId,
                    $ownerItem->owner,
                    $ownerItem
                );
            }
        );

        return $this->message("短信发送成功!");
    }

    /**
     * 根据模板id批量发送短信给管理员
     * @param int $templateId 模板id
     * @param SendService $sendService 发送服务对象
     * @return mixed
     */
    public function sendAdminsByTemplate($templateId)
    {
        $ids = request()->input('ids');

        $query = DB::table('admin_users')->whereNotNull('mobile');

        if ($ids) {
            $query->whereIn('id', $ids);
        }

        $admins = $query->get();

        if (!in_array($templateId, $this->sendService->canSendGroupAdmin())) {
            return $this->failed("非法操作!");
        }

        $boolArr = [];

        foreach ($admins as $admin) {
            // 使用指定模板发送短信给管理员
            $boolArr[] = $this->sendService->qcloudByTemplate($admin->mobile, $templateId, $admin);
        }

        if ($boolArr[0] == true && count(array_unique($boolArr)) === 1) {
            return $this->message("短信发送成功!");
        } else if ($boolArr[0] == false && count(array_unique($boolArr)) === 1) {
            return $this->failed("所有短信发送失败！");
        } else if (count(array_unique($boolArr)) > 1) {
            // 获取发送成功的数量， 获取失败的数量
            $trueCount = 0;
            $falseCount = 0;
            foreach ($boolArr as $value) {
                $value == true ? $trueCount ++ : $falseCount ++;
            }
            return $this->failed("{$trueCount}条短信发送成功，{$falseCount}条发送失败！");
        } else {
            return $this->failed("系统未捕获异常：请联系开发者");
        }
    }

    /**
     * 渲染sms-person界面
     * @param Content $content
     * @return Content
     */
    public function sendPersonCreate(Content $content)
    {
        $form = Form::make(
            new Send(),
            function (Form $form) {
                $form->title("短信发送");
                $form->mobile("mobile", "电话号码");
                $form->select("template_id", "选择模板")->options(SendService::$templateIdMapContext);
                $form->disableEditingCheck();
                $form->disableViewCheck();
                $form->disableCreatingCheck();
                $form->disableListButton();
            }
        );

        return $content->title("推送短信给某人")->body($form);
    }

    /**
     * sms-person界面的post提交方法
     * 根据电话号码编辑短信发送短信给某个人， （该电话号码必须存在于 users表或者admin_users表中）
     * 备注： 在有同手机号码的情况下，有可能会发送错误。
     * @param Request $request
     * @return mixed
     */
    public function sendPersonStore(Request $request)
    {
        $mobile = $request->input("mobile");
        $templateId = $request->input("template_id");

        if (in_array($templateId, $this->sendService->canSendGroupAdmin())) {   // 如果是管理员
            // 第一步先搜索管理员
            $admin = DB::table("admin_users")->where("mobile", $mobile)->first();
            $admin = Administrator::query()->where('username', $admin->username)->where('name', $admin->name)->first();
            if (!$admin) {
                return $this->failed('你选择了管理员模板：该手机号码在管理员列表中不存在');
            }

            // 短信发送
            $this->sendService->qcloudByTemplate($mobile, $templateId, $admin);
        } else {  // 如果是承租人

            $user = User::query()->where("mobile", $mobile)->first();

            if (!$user) {
                return $this->failed('你选择了租客模板：该手机号码在租客列表中不存在');
            }

            $user_id = $user->id;

            // 手机号码校验
            $ownerItem = OwnerItem::query()->with(
                [
                    'owner.user',
                    'owner' => function ($query) use ($user_id) {
                        $query->where('user_id', $user_id)->where('closed', false);
                    },
                ]
            )->whereNull("pay_at")
                ->whereNotNull('total_amount')
                ->where('started_at', '<', Carbon::now())
                ->first();

            if (!$ownerItem) {
                return $this->failed('你选择了租客模板：该租客的合同信息不符合发送短信的条件');
            }

            // 短信发送
            $this->sendService->qcloudByTemplate($mobile, $templateId, $ownerItem->owner, $ownerItem);
        }

        return $this->message("短信发送成功");
    }
}
